package com.example.waimai.serviceImp;

import com.example.waimai.mapper.*;
import com.example.waimai.pojo.*;
import com.example.waimai.service.BossStoreService;
import com.example.waimai.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class BossStoreServiceImp implements BossStoreService {

    @Autowired
    private FoodTypeMapper foodTypeMapper;

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private StoreAddressMapper storeAddressMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OssUtil ossUtil;

    @Override
    public FoodType insertFoodType(FoodType foodType) {
        foodTypeMapper.insertFoodType(foodType);
        System.out.println(foodType.toString());
        return foodType;
    }

    // 删除菜品 相当于更新菜品状态，由1 更新为0
    @Override
    public Boolean deleteFood(Food food) {
        return foodMapper.updateFood(food) == 1;
    }

    @Override
    public Boolean updateFood(Food food) {
        return foodMapper.updateFood(food) == 1;
    }

    @Override
    public String updateStoreImage(MultipartFile image, String id) {
        System.out.println(image);
        String s = null;
        try {
             s = ossUtil.uploadFile(image, "StoreImage-");
       } catch (IOException e) {
            e.printStackTrace();
        }
        if(!"".equals(s)){
            // 进行更新
            Store store = new Store();
            store.setStoreImage(s);
            store.setId(Integer.parseInt(id));
            storeMapper.updateStore(store);
        }
        return s;
    }

    @Override
    public String updateFoodImage(MultipartFile image, String id) {
        String url  = null;
        try{
            url = ossUtil.uploadFile(image,"foodImage-"+id+"-");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(!"".equals(url)){
            Food food = new Food();
            food.setId(Integer.parseInt(id));
            food.setFoodImage(url);
            foodMapper.updateFood(food);
        }
        return url;
    }

    @Override
    public String getImageUrl(MultipartFile image) {
        String url = null;
        try{
            url = ossUtil.uploadFile(image,"foodUrl-");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    @Override
    public Integer addFood(Food food) {
        // 添加菜品，应该返回一个Food 包含 FoodTypeName 的信息
        foodMapper.addFood(food);
        return food.getId();
    }

    @Override
    public Boolean delStore(Integer storeId) {
        Store store = new Store();
        store.setId(storeId);
        store.setStoreStatus(0);
        redisTemplate.delete("store:"+storeId);
        return storeMapper.updateStore(store) == 1;
    }

    @Override
    public List<Store> getAllStore(Integer bossId) {
        return storeMapper.getAllStore(bossId);
    }


    @Override
    public StoreAddress getStoreAddress(Integer storeId) {
        StoreAddress result = null;
        result = (StoreAddress) redisTemplate.opsForValue().get("StoreAddr:"+storeId);
        if(result == null){
            result = storeAddressMapper.getStoreAddressById(storeId);
        }
        return result;
    }

    // 获取订单
    @Override
    public List<Orders> getOrdersByStoreStatus(Integer storeId, Integer storeStatus) {
        List<Orders> result = null;
        if(storeStatus == 2){
            result = ordersMapper.getEndOrders(storeId,storeStatus);
        }else{
            result = ordersMapper.getOrdersByStoreStatus(storeId,storeStatus);
        }
        // 获取到对应的UserAddress
        for(Orders order : result){
            UserAddress userAddress = (UserAddress) redisTemplate.opsForValue().get("userAddr:order:"+order.getId());
            if(userAddress ==null){
                userAddress = userAddressMapper.getAddressByUserAddressId(order.getUserAddressId());
            }
            order.setUserAddress(userAddress);
        }
        return result;
    }



    // 商家接单
    @Override
    public Boolean receiveOrder(Integer orderId) {
        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setStoreStatus(1);
        int result = ordersMapper.updateOrder(orders);
        if(result == 1){
            orders = ordersMapper.getOrderById(orderId); // 获取到订单
            // 获取订单对应的地址信息吧
            // 获取到对应的 UserAddress
            UserAddress userAddress = userAddressMapper.getAddressByUserAddressId(orders.getUserAddressId());
            //  将订单对应的收货地址 存放到对应的 GeoHash中
            String name = "order:"+orderId;
            String key = "missedOrder";

            Point point = new Point(Double.parseDouble(userAddress.getLongitude()),Double.parseDouble(userAddress.getLatitude())) ; // 获取用户地址的经纬度
            RedisGeoCommands.GeoLocation<String> geoLocation = new RedisGeoCommands.GeoLocation<>(name,point); // name + score (这个是HashGeo中的值）
            redisTemplate.opsForGeo().add(key,geoLocation);
        }
        return  result== 1;
    }

    @Override
    public Food getFood(Integer foodId) {
        return foodMapper.getFood(foodId);
    }

    // 上传店铺地址
    @Override
    public Boolean addStoreAddr(StoreAddress storeAddress) {
        Integer result = storeAddressMapper.insert(storeAddress);
        if(result == 1){
            // 附近的店铺 实现 ,也可以利用这个来实现配送范围的选择
            String key = "missedStore";
            String name = "store:"+storeAddress.getStoreId();
            Point point = new Point(Double.parseDouble(storeAddress.getLongitude()),Double.parseDouble(storeAddress.getLatitude()));
            RedisGeoCommands.GeoLocation<String> geoLocation = new RedisGeoCommands.GeoLocation<>(name,point);
            redisTemplate.opsForGeo().add(key,geoLocation);
        }
        return result == 1;
    }

    @Override
    public Store addStore(Store store) {
        Integer result = storeMapper.insertStore(store);
        // 店铺创建完毕后，为店铺创建一个默认的菜品类型
        FoodType foodType = new FoodType();
        foodType.setFoodTypeName("默认类型");
        foodType.setStoreId(store.getId());
        foodTypeMapper.insertFoodType(foodType);
        if(result != 1){
            System.out.println("创建店铺失败");
        }
        return store;
    }

    @Override
    public Boolean realDelStore(Integer storeId) {
        return storeMapper.delStore(storeId) == 1;
    }

    @Override
    public Boolean updateStoreAddr(StoreAddress storeAddress) {
        Integer result = storeAddressMapper.update(storeAddress);
        if(result == 1 && storeAddress.getLongitude() != null && storeAddress.getLatitude() != null){
            // 更新成功
            // 更新一下 Redis里面的数据
            String key = "missedStore";
            String name = "store:"+storeAddress.getStoreId();
            Double longitude = Double.parseDouble(storeAddress.getLongitude());
            Double latitude = Double.parseDouble(storeAddress.getLatitude());
            Point point = new Point(Double.parseDouble(storeAddress.getLongitude()),Double.parseDouble(storeAddress.getLatitude()));
            RedisGeoCommands.GeoLocation<String> geoLocation = new RedisGeoCommands.GeoLocation<>(name,point);
            redisTemplate.opsForGeo().add(key,geoLocation);
        }
        return result == 1;
    }

    @Override
    public Boolean updateStore(Store store) {

        return storeMapper.updateStore(store) == 1;
    }
}
